
/**
 * @author klaoye(K老叶)
 * @email klaoye@163.com
 * @license Apache 2.0
 */
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.util.Objects;

public class FileOperate {

    File filePath;

    public FileOperate(JFrame frame) {// 选择文件路径
        do {
            filePath = Chooser(frame);
        } while (fileFilter("mp3") == null);
    }

    protected File Chooser(JFrame frame) {// 文件选择窗口
        JFileChooser chooser = new JFileChooser();
        FileSystemView systemView = FileSystemView.getFileSystemView();
        chooser.setCurrentDirectory(systemView.getHomeDirectory());
        chooser.setDialogTitle("请选择含有音乐文件的文件夹");
        chooser.setApproveButtonText("选择");
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.showOpenDialog(frame);
        return chooser.getSelectedFile();
    }

    // 文件过滤器
    protected File[] fileFilter(String fileType) {

        File[] files = filePath.listFiles();
        assert files != null;
        File[] files1 = new File[files.length];
        String fileName, fileLastName;
        int l = 0;
        File[] AudioFiles;

        for (File file : files) {
            fileName = file.getName();
            fileLastName = fileName.substring(fileName.indexOf('.') + 1);

            if (fileLastName.equals(fileType)) {
                files1[l++] = file;
            }
        }
        AudioFiles = new File[l];
        System.arraycopy(files1, 0, AudioFiles, 0, l);
        if (Objects.requireNonNull(AudioFiles).length <= 0) {
            System.out.println("这个文件夹不含有" + fileType + "文件");
            return null;
        } else
            return AudioFiles;
    }

}
